'use strict';
import React from "react";
import {StyleSheet, Text, TouchableHighlight, TouchableOpacity, TouchableOpacityComponent, View} from "react-native";
import {inject, observer} from "mobx-react";
import ImageView from "../common/ImageView";
import ListView from "../list/ListView";
import {diffTime} from "../../util/Tool";

@inject('mineStore')
@observer
class MyPublishList extends React.Component {

    constructor(props) {
        super(props);
        this.state = {
            dataSource: [],
        };
        this.page = 1;
        this.limit = 10;
    }

    componentDidMount() {
        this.requestDataSources()
    }

    requestDataSources = async () => {
        const {type, mineStore} = this.props;
        const data = {
            page: this.page,
            limit: this.limit,
            author_id: global.secretKey,
            audit_status: type === 0 ? 'wait' : 'through',
        };
        const result = await mineStore.requestMyPublish(type, data);
        // console.log('我的发布返回-------->', type, result);
        const resData = result.data ? result.data : [];
        this._listViewRef && this._listViewRef.stopRefresh({allLoad: result.data.length < this.limit});
        this._listViewRef && this._listViewRef.stopEndReached({allLoad: resData.length < this.limit}); // 是否加载完毕需要自行判断
    };

    _onPressItem = (item) => {
        const {type} = this.props;
        if (type === 1) { //审核通过才能进入详情
            if (item.article_type === '2') { //视频
                RouterHelper.navigate('', 'VideoDetail', {information_id: item.information_id});
            } else { //文章
                RouterHelper.navigate('', 'ArticleDetails', {information_id: item.information_id});
            }
        }
    };

    renderItem = (info) => {
        const {item, index} = info;
        const width = SCREEN_WIDTH * 0.28;
        const height = width * 0.667;
        return (
            <TouchableOpacity
                onPress={() => {
                    this._onPressItem(item)
                }}
                activeOpacity={1}
                style={styles.itemContainer}>
                <View style={styles.content}>
                    <View style={styles.itemInfoCon}>
                        <Text style={styles.titleText}>{item.information_title}</Text>
                        <View style={styles.bottomInfo}>
                            <Text style={styles.itemTime}>{diffTime(item.publish_time)}</Text>
                        </View>
                    </View>
                    <ImageView
                        resizeMode={'cover'}
                        style={[styles.image, {width, height}]}
                        source={item.cover_url ? {uri: item.cover_url} : Images.img_shop_default}
                    />
                </View>
            </TouchableOpacity>
        )
    };

    _onRefresh = (stopRefresh) => {
        this.page = 1;
        this.requestDataSources()
    };

    _onEndReached = (stopEndReached) => {
        this.page++;
        this.requestDataSources()
    };

    _keyExtractor = (item, index) => {
        return `item${index}`
    };

    _captureRef = (v) => {
        this._listViewRef = v
    };

    _deleteItem = async (item, index) => {
        const {mineStore, type} = this.props;
        let type_text = type === 0 ? 'wait' : 'through';
        let params = {
            title: '温馨提示',
            detail: '文章或视频删除后将不可恢复，请确认？',
            actions: [
                {
                    title: '取消',
                    onPress: () => {
                    }
                },
                {
                    title: '确定',
                    onPress: async () => {
                        let url = ServicesApi.PUBLISH_DEL;
                        let data = {
                            information_id: item.information_id
                        };
                        let result = await Services.post(url, data);
                        if (result.code === StatusCode.SUCCESS_CODE) {
                            mineStore.removePublishItem(type_text, index);
                            ToastManager.show('删除成功');
                        }
                    }
                },
            ]
        };
        AlertManager.show(params);

    };

    _editItem = async (item) => {
        // console.log('编辑');
        //先获取详情中的视频，图片信息
        const data = {
            focus_user: global.secretKey,
            information_id: item.information_id,
        };
        const result = await Services.post(ServicesApi.INFORMATION_DETAIL, data);
        // console.log('编辑详情返回---------->', result);
        if (result.code === StatusCode.SUCCESS_CODE) {
            let arrs = [];
            if (item.article_type === '2') { //视频
                if (Array.isArray(result.data.videoVOs)) {
                    result.data.videoVOs.map((item, i) => {
                        arrs.push(item.video_url);
                    })
                }
                item.video_key = arrs.join(',');
                RouterHelper.navigate('', 'PublishVideo', {
                    item,
                    onCallBack: () => this._onRefresh()
                });
            } else { //文章
                if (Array.isArray(result.data.imageVOs)) {
                    result.data.imageVOs.map((item, i) => {
                        arrs.push({
                            source: item.image_url
                        });
                    })
                }
                item.image_key = arrs;
                RouterHelper.navigate('', 'PublishArticle', {
                    item,
                    onCallBack: () => this._onRefresh()
                });
            }
        }
    };

    _getQuickActions = ({item, index}) => {
        const {type} = this.props;
        return <View style={styles.quickAContent}>
            {type === 0 ?
                <TouchableHighlight
                    onPress={() => this._editItem(item)}
                >
                    <View style={styles.quickEdit}>
                        <Text style={styles.delete}>编辑</Text>
                    </View>
                </TouchableHighlight> : null}
            <TouchableHighlight
                onPress={() => this._deleteItem(item, index)}
            >
                <View style={styles.quick}>
                    <Text style={styles.delete}>删除</Text>
                </View>
            </TouchableHighlight>
        </View>
    };

    render() {
        const {type, mineStore} = this.props;
        return (
            <ListView
                style={styles.listContent}
                listType={'SwipeableFlatList'}
                ref={this._captureRef}
                initialRefresh={false}
                enableLoadMore={true}
                enableRefresh={true}
                data={type === 0 ? mineStore.getMyPublish['wait'] : mineStore.getMyPublish['through']}
                keyExtractor={this._keyExtractor}
                renderItem={this.renderItem}
                onRefresh={this._onRefresh}
                onEndReached={this._onEndReached}
                maxSwipeDistance={type === 0 ? 120 : 60}
                getQuickActions={this._getQuickActions}
            />
        );
    }
}

const styles = StyleSheet.create({
    listContent: {
        backgroundColor: '#f5f5f5',
    },
    itemContainer: {
        marginTop: 5,
        alignItems: 'center',
        flexDirection: 'column',
        backgroundColor: '#fff',
    },
    content: {
        flexDirection: 'row',
        justifyContent: 'center',
        // backgroundColor: "#9f1f1f"
    },
    itemInfoCon: {
        flex: 1,
        marginTop: 13,
        marginBottom: 13,
        marginRight: 46,
        marginLeft: 15,
        justifyContent: 'space-between',
    },
    titleText: {
        fontSize: FontSize(12),
        color: "#4a4a4a"
    },
    bottomInfo: {
        justifyContent: 'space-between',
        flexDirection: 'row',
        alignItems: 'center',
    },
    itemTime: {
        fontSize: FontSize(10),
        color: "#929292"
    },
    itemBottomName: {
        fontSize: FontSize(10),
        color: "#929292",
        // height: 60,
    },
    image: {
        marginTop: 13,
        marginBottom: 13,
        marginRight: 10,
        borderRadius: 5,
    },
    //侧滑菜单的样式
    quickAContent: {
        flex: 1,
        marginTop: 5,
        flexDirection: 'row',
        justifyContent: 'flex-end',
    },
    quick: {
        flex: 1,
        width: 60,
        alignItems: 'center',
        justifyContent: 'center',
        backgroundColor: "#ff3c32",

    },
    quickEdit: {
        flex: 1,
        width: 60,
        alignItems: 'center',
        justifyContent: 'center',
        backgroundColor: "#ffa64f",

    },
    delete: {
        color: "#fff",
    },
});

export default MyPublishList